<?php
/**
 * Created by PhpStorm.
 * User: jim
 * Date: 2017-01-04
 * Time: 19:19
 */

namespace App\Http\Controllers\home;


use App\Http\Controllers\Controller;
use App\Models\M3Result;
use App\Models\Order;
use App\Models\Order_time;
use App\Org\wxpay\WXTool;
use Log;
use Illuminate\Http\Request;

class PayController extends Controller
{
    //微信支付
    public function wxPay(Request $request) {
		//dd($request->input('name'), $request->input('order_no'), $request->input('total_price'));
		
        $openid = $request->session()->get('openid', '');
        if($openid == '') {
            $m3_result = new M3Result;
            $m3_result->status = 1;
            $m3_result->message = 'Session已过期, 请重新提交订单';
            return $m3_result;
        }
        return WXTool::wxPayData($request->input('name'), $request->input('order_no'), $request->input('total_price'), $openid);
    }
    //微信支付回调
    public function wxNotify() {
        Log::info('微信支付回调开始');
        $return_data = file_get_contents("php://input");
        Log::info('return_data: '.$return_data);

        libxml_disable_entity_loader(true);
        $data = simplexml_load_string($return_data, 'SimpleXMLElement', LIBXML_NOCDATA);

        Log::info('return_code: '.$data->return_code);
        if($data->return_code == 'SUCCESS') {
            $order = Order::where('number', $data->out_trade_no)->first();
            $order_time = Order_time::where('order_id',$order->id)->first();
            $order->status = 2;
            $order->state=2;
            $time=date('Y-m-d H:i:s',time());
            $order_time->pay_at=$time;
            $order->save();
            $order_time->save();
            Log::info('order_id: '.$order->id);
            Log::info('order_time: '.$time);
            return "<xml>
                <return_code><![CDATA[SUCCESS]]></return_code>
                <return_msg><![CDATA[OK]]></return_msg>
              </xml>";
        }

        return "<xml>
              <return_code><![CDATA[FAIL]]></return_code>
              <return_msg><![CDATA[FAIL]]></return_msg>
            </xml>";

    }
}